package com.lnsoft.cac.server.handle.codec.frameMessage;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.Data;
import lombok.NonNull;

import java.util.ArrayList;
import java.util.List;

@Data
/**
 * 监测数据-电压数据报内容详情
 * */
public class    Voltage_Msg {
    private int Measure_Point_ID;       //1byte     监测点号（无符号整数）
    private int MeasureData_Num;        //1byte     监测数据个数（无符号整数）
    private List<Voltage_Data> MeasureDataList;     //  数据条目

    public ByteBuf toByteBuf() throws Exception{
        if (!Util.measurePointIDIsAvailable(Measure_Point_ID)) {
            throw new Exception("监测点号设置异常");
        }
        if (!Util.measureDataNumIsAvailable(MeasureData_Num)) {
            throw new Exception("监测数据个数设置异常");
        }
        if (MeasureDataList == null) {
            MeasureDataList = new ArrayList<>();
        }
        if (MeasureData_Num != MeasureDataList.size()) {
            throw new Exception("监测数据个数设置异常");
        }
        ByteBuf bf = Unpooled.buffer(1453);
        bf.writeByte(Measure_Point_ID);
        bf.writeByte(MeasureData_Num);
        for (Voltage_Data item : MeasureDataList) {
            bf.writeBytes(item.toByteBuf());
        }
        return bf;
    }

    //  解析 [监测数据-电压数据] 帧报文内容区 到消息体中
    public static Voltage_Msg decFrameBody(@NonNull byte[] frameBody) throws Exception {
        ByteBuf bf = Unpooled.wrappedBuffer(frameBody);
        Voltage_Msg msg = new Voltage_Msg();
        int len = frameBody.length;
        if (len == 0) {
            return null;
        }
        int num = bf.getUnsignedByte(1);
        if ((num * 8 + 2) != len) {
            throw new Exception("frameBody 数据异常");
        }
        msg.setMeasure_Point_ID(bf.getUnsignedByte(0));
        msg.setMeasureData_Num(num);
        List<Voltage_Data> list = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            Voltage_Data item = new Voltage_Data();
            item.setStatTime(bf.getIntLE(2 + i * 8) & 0xFFFFFFFF);
            byte[] vol = new byte[4];
            bf.getBytes(6 + i * 8, vol);
            item.setVoltage(vol);
            list.add(item);
        }
        msg.setMeasureDataList(list);
        return msg;
    }
}
